#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''
import logging
import json
from pycommon import Const
from pycommon import Pack as packet
import GameManager
import CenterBuild
import CounterManager
import UserManager
import HallInfoManager
import CenterCtxManager
import GateFactory
import TableManager
import GameDb

def cmdGameLogin(game,pkt):
    sid,ip,port,relogin = packet.unpack("HsHB",pkt)
    valid = GameManager.instance.checkGameSidValid(sid)
    if valid:
        game.onLogin(sid,ip,port)
        GameManager.instance.gameLogin(sid,ip,port)#广播通知Gate服务器 所有Game信息
        game.sendPacket(CenterBuild.gameLoginCenterSucess())
        if relogin == 0:
            #游戏服务器重启或者第一次连接
            CounterManager.instance.addCount(Const.COUNTER_GAME_SERVER_RELOGIN)
            alluser = UserManager.instance.getAllUserBySid(sid)
            for u in alluser:
                UserManager.instance.userExitGame(u.getUid())
        else:
            #游戏服务器重连
            logging.debug(u"gameserver login center sid = %d relogin = %d",sid,relogin)
    else:
        logging.debug(u"sid=%d started,you can changed the sid and retry",sid)
        game.abort()

def cmdGameHallInfo(game,pkt):
    jstr = packet.unpack("S", pkt)
    hallinfos = json.loads(jstr)
    logging.debug("cmdGameHallInfo hallInfo=%s",hallinfos)
    sid = game.getSId()
    HallInfoManager.instance.update(sid,game.getSIp(),game.getSPort(),hallinfos)

def cmdCreateTable(game,pkt):
    code,ctxId,hallId,tableId = packet.unpack("HHHH",pkt)
    logging.debug("cmdCreateTable = %d",code)
    ct = CenterCtxManager.instance.popCtx(ctxId)
    if ct == None:
        logging.warn("CenterCtxManager popCtx id = %d is None",ctxId)
        return
    gate = GateFactory.instance.getGateSrvBySid(ct.gatesid)
    if code != Const.ERR_OK:
        logging.debug(u"gameparse createTableError popId = %d uid = %d",ctxId,ct.uid)
        gate.transPkt2Client(ct.uid, CenterBuild.sendCreateTableToClient(code,''))
    else:
        ip = game.getSIp()
        port = game.getSPort()
        TableManager.instance.initTable(ct.uid,tableId,ip,port,ct.maxRound,ct.tableModel,ct.playModel,ct.cardId,ct.cardNum,ct.hallId,ct.tableIdStr)
        gate.transPkt2Client(ct.uid, CenterBuild.sendCreateTableToClient(code,ct.tableIdStr))
        user = UserManager.instance.getUser(ct.uid)
        user.useProp(ct.cardId,ct.cardNum,way = Const.PROP_CHANGE_USE)
    pass

def cmdEnterTable(game,pkt):
    tableIdStr,uid = packet.unpack("sI",pkt)
    TableManager.instance.enterTable(tableIdStr,uid)
    logging.debug("game->center uid=%d enter tableIdStr=%s sucess",uid,tableIdStr)


def cmdCheckUser(game,pkt):
    uid, session, pid = packet.unpack("IsH", pkt)
    logging.debug(u"!!!!!!!!!!!!!!cmdCheckUser() uid=%d, session=%s, pid=%d",uid,session,pid,)
    user = UserManager.instance.getUser(uid)
    if user:
        if session != user.getSession():
            game.sendPacket(CenterBuild.checkUser(Const.ERR_SESSION_WRONG,uid,session,pid))
        else:
            user.checkUserSuc(game.getSId(),session,pid)
    else:
        game.sendPacket(CenterBuild.checkUser(Const.ERR_UID_WRONG,uid,session,pid))
        logging.debug(u"uid=%d not login center",uid)
    pass

def cmdUserLogin(game,pkt):
    uid,hallid = packet.unpack("IH", pkt)
    logging.debug(u"cmdUserLogin() uid=%d hallid=%d",uid,hallid)
    user = UserManager.instance.getUser(uid)
    if not user:
        logging.warn(u"cmdUserLogin(), getUser() return None, uid=%d",uid)
        return
    logging.debug("getSId() = %d getGameSid()=%d",game.getSId(),user.getGameSid())
    if game.getSId() != user.getGameSid():
        logging.warn(u"cmdUserLogin(), gamesrv.getSId() != user.getGameSid(), uid=%d",uid)
        return
    user.userLoginGame(game.getSId())
    logging.debug("uid=%d login gameid=%d sucess",uid,user.gamesid)

def cmdUserLogout(game,pkt):
    uid,reason,isDropUser = packet.unpack("IBB", pkt)
    log = {0:"USER_LEAVE_LOGOUT",1:"USER_LEAVE_CON_LOST",2:"USER_LEAVE_KICK",3:"USER_LEAVE_CENTER_APPLY"}
    logging.debug(u'cmdUserLogout uid=%d reason = %d:%s isDropUser = %d',uid,reason,log.get(reason,""),isDropUser)
    user = UserManager.instance.getUser(uid)
    user.userLogoutGame()
    if isDropUser == 0:
        TableManager.instance.userLogoutGame(uid)
    pass

def cmdReportHall(game,pkt):
    count = packet.unpack("H",pkt)
    result = {}
    for i in range(count):
        index = i*(2+2) + 2
        hid,count = packet.unpack("HH",pkt,index)
        result[hid] = count
        logging.debug("cmdReportHall hid=%d count=%d",hid,count)
    HallInfoManager.instance.tickUpdateHall(game.getSId(),result)
    pass

def cmdTableDismiss(game,pkt):
    GameDb.instance.updateProp(0, 0,10,Const.PROP_CHANGE_BACK)

#================================Ð­Òé±í===========================================
    
__cmdTable = {
                Const.CMD_GAME2CT_LOGIN          : cmdGameLogin,
                Const.CMD_GAME2CT_HALL_INFO      : cmdGameHallInfo,
                Const.CMD_GAME2CT_CREATE_TABLE   : cmdCreateTable,
                Const.CMD_GAME2CT_ENTER_TABLE    : cmdEnterTable,
                Const.CMD_GAME2CT_CHECK_USER     : cmdCheckUser,
                Const.CMD_GAME2CT_USER_LOGIN     : cmdUserLogin,
                Const.CMD_GAME2CT_USER_LOGOUT    : cmdUserLogout,
                Const.CMD_GAME2CT_REPORT_HALL    : cmdReportHall,
                Const.CMD_GAME2CT_TABLE_DISMISS  : cmdTableDismiss
             } 

def parse(gate, cmd, pkt):
    logging.debug(u"GameParse cmd = %d",cmd)
    func = __cmdTable.get(cmd)
    if not func :
        logging.error(u"cmd is not exit");
    func(gate, pkt)    
    
if __name__ == '__main__':
    pass